import './watcher.js';
import getModifiedData from '../../lib/modified';

describe('Component vnWatcher', () => {
    let $scope;
    let $element;
    let $state;
    let $httpBackend;
    let controller;
    let $attrs;
    let $q;

    beforeEach(ngModule('vnCore'));

    beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _$state_, _$q_) => {
        $scope = $rootScope.$new();
        $element = angular.element('<div></div>');
        $state = _$state_;
        $q = _$q_;
        $httpBackend = _$httpBackend_;
        $attrs = {
            save: 'patch'
        };
        controller = $componentController('vnWatcher', {$scope, $element, $state, $httpBackend, $attrs, $q});
    }));

    describe('$onInit()', () => {
        it(`should call fetchData() if controllers get and url properties are defined`, () => {
            controller.get = () => {};
            controller.url = 'test.com';
            spyOn(controller, 'fetchData');
            controller.$onInit();

            expect(controller.fetchData).toHaveBeenCalledWith();
        });

        it(`should throw an error if $onInit is called without url defined`, () => {
            controller.get = () => {};

            expect(function() {
                controller.$onInit();
            }).toThrowError(/parameter/);
        });
    });

    describe('fetchData()', () => {
        it(`should perform a query then store the received data into controller.data and call updateOriginalData()`, () => {
            spyOn(controller, 'updateOriginalData');
            let json = {data: 'some data'};
            controller.data = [1];
            controller.idField = 0;
            controller.url = 'test.com';
            $httpBackend.whenGET('test.com/1').respond(json);
            $httpBackend.expectGET('test.com/1');
            controller.fetchData();
            $httpBackend.flush();

            expect(controller.data).toEqual({data: 'some data'});
            expect(controller.updateOriginalData).toHaveBeenCalledWith();
        });
    });

    describe('submitBack()', () => {
        it(`should call controller.window.history.back() function after calling controllers submit() function`, done => {
            spyOn(controller, 'submit').and.returnValue(Promise.resolve());
            spyOn(controller.window.history, 'back');
            controller.submitBack()
                .then(() => {
                    expect(controller.submit).toHaveBeenCalledWith();
                    expect(controller.window.history.back).toHaveBeenCalledWith();
                    done();
                }).catch(done.fail);
        });
    });

    describe('submitGo()', () => {
        it(`should call controller.$state.go() function after calling controllers submit() function`, done => {
            spyOn(controller, 'submit').and.returnValue(Promise.resolve());
            spyOn(controller.$state, 'go');
            let state = 'the.State';
            controller.submitGo(state)
                .then(() => {
                    expect(controller.submit).toHaveBeenCalledWith();
                    expect(controller.$state.go).toHaveBeenCalledWith(state, {});
                    done();
                }).catch(done.fail);
        });
    });

    describe('check()', () => {
        it(`should throw error if controller.form is invalid`, () => {
            controller.form = {$invalid: true};

            expect(function() {
                controller.check();
            }).toThrowError();
        });

        it(`should throw error if controller.dirty is true`, () => {
            controller.form = {$invalid: true};

            expect(function() {
                controller.check();
            }).toThrowError();
        });
    });

    describe('realSubmit()', () => {
        describe('when controller.form', () => {
            it(`should call controller.form.setSubmited if controller.form is defined`, () => {
                controller.form = {
                    $setSubmitted: () => {},
                    $setPristine: () => {}
                };
                spyOn(controller.form, '$setSubmitted');
                controller.realSubmit();

                expect(controller.form.$setSubmitted).toHaveBeenCalledWith();
            });
        });

        describe('when controller.save()', () => {
            it(`should set controller.save.model property`, () => {
                controller.save = {accept: () => $q.resolve()};
                controller.data = {originalInfo: 'original data', info: 'new data'};
                controller.orgData = {originalInfo: 'original data'};
                controller.realSubmit();

                expect(controller.save.model).toEqual({info: 'new data'});
            });
        });

        describe('when id is defined', () => {
            it(`should perform a query then call controller.writeData()`, done => {
                controller.dataChanged = () => {
                    return true;
                };
                controller.data = {id: 2};
                controller.orgData = {id: 1};
                let changedData = getModifiedData(controller.data, controller.orgData);
                controller.idField = 'id';
                controller.url = 'test.com';
                let json = {data: 'some data'};
                spyOn(controller, 'writeData').and.callThrough();
                $httpBackend.whenPATCH(`${controller.url}/1`, changedData).respond(json);
                $httpBackend.expectPATCH(`${controller.url}/1`);
                controller.realSubmit()
                    .then(() => {
                        expect(controller.writeData).toHaveBeenCalledWith(jasmine.any(Object), jasmine.any(Function));
                        done();
                    }).catch(done.fail);
                $httpBackend.flush();
            });
        });

        it(`should perform a POST query then call controller.writeData()`, done => {
            controller.dataChanged = () => {
                return true;
            };
            controller.data = {id: 2};
            controller.orgData = {id: 1};
            controller.url = 'test.com';
            let json = {data: 'some data'};
            spyOn(controller, 'writeData').and.callThrough();
            $httpBackend.whenPOST(`${controller.url}`, controller.data).respond(json);
            $httpBackend.expectPOST(`${controller.url}`, controller.data);
            controller.realSubmit()
                .then(() => {
                    expect(controller.writeData).toHaveBeenCalledWith(jasmine.any(Object), jasmine.any(Function));
                    done();
                }).catch(done.fail);
            $httpBackend.flush();
        });
    });

    describe('writeData()', () => {
        it(`should call Object.asssign() function over controllers.data with json.data, then call updateOriginalData function and finally call resolve() function`, () => {
            spyOn(controller, 'updateOriginalData');
            controller.data = {};
            let json = {data: 'some data'};
            let resolve = jasmine.createSpy('resolve');
            controller.writeData(json, resolve);

            expect(controller.updateOriginalData).toHaveBeenCalledWith();
            expect(resolve).toHaveBeenCalledWith(json);
        });
    });

    describe('callback()', () => {
        describe(`when dataChanged() returns true and there's no state in the controller`, () => {
            it(`should define controller.state, call controller.$.confirm.show() and return false`, () => {
                $scope.confirm = {show: jasmine.createSpy('show')};
                controller.dataChanged = () => {
                    return true;
                };
                controller.state = undefined;
                let transition = {to: () => {
                    return {name: 'Batman'};
                }};
                let result = controller.callback(transition);

                expect(controller.state).toEqual('Batman');
                expect(controller.$.confirm.show).toHaveBeenCalledWith();
                expect(result).toBeFalsy();
            });
        });

        describe(`when dataChanged() returns false and/or there's a state in the controller`, () => {
            it(`should return true`, () => {
                $scope.confirm = {show: jasmine.createSpy('show')};
                controller.dataChanged = () => {
                    return false;
                };
                controller.state = 'the state';
                let transition = {to: () => {
                    return {name: 'Batman'};
                }};
                let result = controller.callback(transition);

                expect(result).toBeTruthy();
            });
        });
    });

    describe(`onConfirmResponse()`, () => {
        describe(`when response is accept`, () => {
            it(`should call Object.assing on controlle.data with controller.orgData then call go() on state`, () => {
                let response = 'accept';
                controller.data = {};
                controller.orgData = {name: 'Batman'};
                controller.$state = {go: jasmine.createSpy('go')};
                controller.state = 'Batman';
                controller.onConfirmResponse(response);

                expect(controller.data).toEqual(controller.orgData);
                expect(controller.$state.go).toHaveBeenCalledWith(controller.state);
            });
        });

        describe(`when response is not accept`, () => {
            it(`should set controller.state to null`, () => {
                let response = 'anything but accept';
                controller.state = 'Batman';
                controller.onConfirmResponse(response);

                expect(controller.state).toBeFalsy();
            });
        });
    });

    describe(`loadOriginalData()`, () => {
        it(`should iterate over the current data object, delete all properties then assign the ones from original data`, () => {
            controller.data = {name: 'Bruce'};
            controller.orgData = {name: 'Batman'};
            controller.loadOriginalData();

            expect(controller.data).toEqual(controller.orgData);
        });
    });
});