import eqArrays from './eqArrays';
import { objectInterface } from './interfaces';


// interface objectInterface {[key:string]: any };
const primatives:[string, string, string] = ['number', 'string', 'boolean'];


const isObjectButNotArray = (obj:objectInterface) => {
	return typeof obj === 'object' && !Array.isArray(obj);
}

const eqObjects = (object1:objectInterface, object2:objectInterface):boolean => {
	const obj1Keys:string[] = Object.keys(object1).sort();
	const obj2Keys:string[] = Object.keys(object2).sort();

	if (obj1Keys.length !== obj2Keys.length) {
		return false;
	}

	if (!eqArrays(obj1Keys, obj2Keys)) {
		return false;
	}

	for (let key of obj1Keys) {
		// if they are primative types
		if (primatives.indexOf(typeof object1[key]) !== -1 &&  primatives.indexOf(typeof object2[key]) !== -1) {
			if (object1[key] !== object2[key]) return false;
		} else {
			// if both arrays
			if (Array.isArray(object1[key]) && Array.isArray(object2[key]) ) {
				if (!eqArrays(object1[key], object2[key])) {
					return false;
				}
			} else if (isObjectButNotArray(object1[key]) && isObjectButNotArray(object2[key])) {
				if (!eqObjects(object1[key], object2[key])) {
					return false;
				}
			} else {
				return false;
			}
		}
	}
	return true;
}

export default eqObjects;

// const ab = { a: "1", b: "2" };
// const ba = { b: "2", a: "1" };
// console.log(eqObjects(ab, ba)); // => true

// const abc = { a: "1", b: "2", c: "3" };
// console.log(eqObjects(ab, abc)); // => false

// const cd = { c: "1", d: ["2", 3] };
// const dc = { d: ["2", 3], c: "1" };
// console.log(eqObjects(cd, dc)); // => true

// const cd2 = { c: "1", d: ["2", 3, 4] };
// console.log(eqObjects(cd, cd2)); // => false
// console.log(eqObjects({ a: { z: 1 }, b: 2 }, { a: { z: 1 }, b: 2 })); // => true
// console.log(eqObjects({ a: { y: 0, z: 1 }, b: 2 }, { a: { z: 1 }, b: 2 })); // => false
// console.log(eqObjects({ a: { y: 0, z: 1 }, b: 2 }, { a: 1, b: 2 })); // => false