import './index.js';

describe('Ticket Component vnTicketDescriptorMenu', () => {
    let $httpBackend;
    let $httpParamSerializer;
    let controller;
    let $state;

    const ticket = {
        id: 16,
        clientFk: 1101,
        invoiceOut: {id: 1},
        client: {
            id: 1101,
            email: 'client@email'
        },
        address: {
            id: 1101,
            mobile: 111111111,
            phone: 2222222222
        },
        tracking: {
            state: {alertLevel: 3}
        }
    };

    beforeEach(ngModule('ticket'));

    beforeEach(inject(($componentController, _$httpBackend_, _$httpParamSerializer_, _$state_) => {
        $httpBackend = _$httpBackend_;
        $httpParamSerializer = _$httpParamSerializer_;
        $state = _$state_;
        $state.params.id = 16;
        $state.getCurrentPath = () => [null, {state: {name: 'ticket'}}];

        const $element = angular.element('<vn-ticket-descriptor-menu></vn-ticket-descriptor-menu>');
        controller = $componentController('vnTicketDescriptorMenu', {$element});
        controller._ticketId = ticket.id;
        controller._id = ticket.id;
        controller.ticket = ticket;
    }));

    describe('canRestoreTicket() getter', () => {
        it('should return true for a ticket deleted within the last hour', () => {
            controller.ticket.isDeleted = true;
            controller.ticket.updated = Date.vnNew();

            const result = controller.canRestoreTicket;

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

        it('should return false for a ticket deleted more than one hour ago', () => {
            const pastHour = Date.vnNew();
            pastHour.setHours(pastHour.getHours() - 2);

            controller.ticket.isDeleted = true;
            controller.ticket.updated = pastHour;

            const result = controller.canRestoreTicket;

            expect(result).toBeFalsy();
        });
    });

    describe('addTurn()', () => {
        it('should make a query and call $.addTurn.hide() and vnApp.showSuccess()', () => {
            controller.$.addTurn = {hide: () => {}};
            jest.spyOn(controller.$.addTurn, 'hide');

            $httpBackend.expectPATCH(`TicketWeeklies`).respond();
            controller.addTurn(1);
            $httpBackend.flush();

            expect(controller.$.addTurn.hide).toHaveBeenCalledWith();
        });
    });

    describe('deleteTicket()', () => {
        it('should make a query and call vnApp.showSuccess()', () => {
            jest.spyOn(controller, 'reload').mockReturnThis();
            jest.spyOn(controller.vnApp, 'showSuccess');

            $httpBackend.expectPOST(`Tickets/${ticket.id}/setDeleted`).respond();
            controller.deleteTicket();
            $httpBackend.flush();

            expect(controller.reload).toHaveBeenCalled();
            expect(controller.vnApp.showSuccess).toHaveBeenCalled();
        });

        it(`should make a query and call showSuccess() after state.go if the state wasn't inside ticket module`, () => {
            jest.spyOn(controller, 'reload').mockReturnThis();
            jest.spyOn(controller.$state, 'go').mockReturnValue('ok');
            jest.spyOn(controller.vnApp, 'showSuccess');
            controller.$state.current.name = 'ticket.card.something';

            $httpBackend.expectPOST(`Tickets/${ticket.id}/setDeleted`).respond();
            controller.deleteTicket();
            $httpBackend.flush();

            expect(controller.reload).toHaveBeenCalled();
            expect(controller.$state.go).toHaveBeenCalledWith('ticket.index');
            expect(controller.vnApp.showSuccess).toHaveBeenCalled();
        });
    });

    describe('restoreTicket()', () => {
        it('should make a query to restore the ticket and call vnApp.showSuccess()', () => {
            jest.spyOn(controller, 'reload').mockReturnThis();
            jest.spyOn(controller.vnApp, 'showSuccess');

            $httpBackend.expectPOST(`Tickets/${ticket.id}/restore`).respond();
            controller.restoreTicket();
            $httpBackend.flush();

            expect(controller.reload).toHaveBeenCalled();
            expect(controller.vnApp.showSuccess).toHaveBeenCalled();
        });
    });

    describe('showPdfDeliveryNote()', () => {
        it('should open a new window showing a delivery note PDF document', () => {
            jest.spyOn(window, 'open').mockReturnThis();
            const type = 'deliveryNote';
            const expectedParams = {
                recipientId: ticket.client.id,
                type: type
            };
            const serializedParams = $httpParamSerializer(expectedParams);
            const expectedPath = `api/tickets/${ticket.id}/delivery-note-pdf?${serializedParams}`;
            controller.showPdfDeliveryNote(type);

            expect(window.open).toHaveBeenCalledWith(expectedPath);
        });
    });

    describe('sendPdfDeliveryNote()', () => {
        it('should make a query and call vnApp.showMessage()', () => {
            jest.spyOn(controller.vnEmail, 'send');

            const $data = {email: 'brucebanner@gothamcity.com'};
            const params = {
                id: 16,
                recipient: $data.email,
                recipientId: ticket.client.id
            };
            controller.sendPdfDeliveryNote($data);

            const expectedPath = `tickets/${ticket.id}/delivery-note-email`;

            expect(controller.vnEmail.send).toHaveBeenCalledWith(expectedPath, params);
        });
    });

    describe('showCsvDeliveryNote()', () => {
        it('should make a query to the csv delivery-note download endpoint and show a message snackbar', () => {
            jest.spyOn(window, 'open').mockReturnThis();

            const expectedParams = {
                recipientId: ticket.client.id
            };
            const serializedParams = $httpParamSerializer(expectedParams);
            const expectedPath = `api/tickets/${ticket.id}/delivery-note-csv?${serializedParams}`;
            controller.showCsvDeliveryNote();

            expect(window.open).toHaveBeenCalledWith(expectedPath);
        });
    });

    describe('sendCsvDeliveryNote()', () => {
        it('should make a query to the csv delivery-note send endpoint and show a message snackbar', () => {
            jest.spyOn(controller.vnEmail, 'send');

            const $data = {email: 'brucebanner@gothamcity.com'};
            const expectedParams = {
                recipient: $data.email,
                recipientId: ticket.client.id,
            };
            controller.sendCsvDeliveryNote($data);

            const expectedPath = `tickets/${ticket.id}/delivery-note-csv-email`;

            expect(controller.vnEmail.send).toHaveBeenCalledWith(expectedPath, expectedParams);
        });
    });

    describe('makeInvoice()', () => {
        it('should make a query and call $state.reload() method', () => {
            jest.spyOn(controller, 'reload').mockReturnThis();
            jest.spyOn(controller.vnApp, 'showSuccess');

            const expectedParams = {ticketsIds: [ticket.id]};
            $httpBackend.expectPOST(`Tickets/invoiceTicketsAndPdf`, expectedParams).respond();
            controller.makeInvoice();
            $httpBackend.flush();

            expect(controller.reload).toHaveBeenCalledWith();
            expect(controller.vnApp.showSuccess).toHaveBeenCalled();
        });

        it('should show withoutWeightConfirmation', () => {
            controller.$.withoutWeightConfirmation = {show: () => {}};
            jest.spyOn(controller.$.withoutWeightConfirmation, 'show');
            controller.ticket.address.incotermsFk = true;

            controller.makeInvoice();
            controller.ticket.address.incotermsFk = false;

            expect(controller.$.withoutWeightConfirmation.show).toHaveBeenCalled();
        });
    });

    describe('createPdfInvoice()', () => {
        it('should make a query and show a success snackbar', () => {
            jest.spyOn(controller.vnApp, 'showSuccess');

            $httpBackend.whenPOST(`Docuwares/${ticket.id}/checkFile`).respond();
            $httpBackend.whenGET(`Tickets/${ticket.id}`).respond();
            $httpBackend.expectPOST(`InvoiceOuts/${ticket.invoiceOut.id}/createPdf`).respond();
            controller.createPdfInvoice();
            $httpBackend.flush();

            expect(controller.vnApp.showSuccess).toHaveBeenCalled();
        });
    });

    describe('changeShipped()', () => {
        it('should make a query and change the shipped hour if the response is accept', () => {
            jest.spyOn(controller, 'reload').mockReturnThis();
            jest.spyOn(controller.vnApp, 'showSuccess');

            $httpBackend.expectPOST(`Tickets/${ticket.id}/updateEditableTicket`).respond();
            controller.changeShipped();
            $httpBackend.flush();

            expect(controller.reload).toHaveBeenCalled();
            expect(controller.vnApp.showSuccess).toHaveBeenCalled();
        });
    });

    describe('recalculateComponents()', () => {
        it('should make a query and show a success message', () => {
            jest.spyOn(controller, 'reload').mockReturnThis();
            jest.spyOn(controller.vnApp, 'showSuccess');

            $httpBackend.expect('POST', `Tickets/${ticket.id}/recalculateComponents`).respond();
            controller.recalculateComponents();
            $httpBackend.flush();

            expect(controller.reload).toHaveBeenCalled();
            expect(controller.vnApp.showSuccess).toHaveBeenCalled();
        });
    });

    describe('refund()', () => {
        it('should make a query and go to ticket.card.sale', () => {
            controller.$state.go = jest.fn();

            controller._id = ticket.id;

            const params = {
                ticketsIds: [16]
            };
            const response = {id: 99};
            $httpBackend.expectPOST('Tickets/refund', params).respond([response]);
            controller.refund();
            $httpBackend.flush();

            expect(controller.$state.go).toHaveBeenCalledWith('ticket.card.sale', response);
        });
    });

    describe('sendChangesSms()', () => {
        it('should make a query and open the sms dialog', () => {
            controller.$.sms = {open: () => {}};
            jest.spyOn(controller.$.sms, 'open');

            $httpBackend.expectGET(`TicketLogs/${ticket.id}/getChanges`).respond();
            controller.sendChangesSms();
            $httpBackend.flush();

            expect(controller.$.sms.open).toHaveBeenCalledWith();
        });
    });

    describe('showSMSDialog()', () => {
        it('should set the destionationFk and destination properties and then call the sms open() method', () => {
            controller.$.sms = {open: () => {}};
            controller.showSMSDialog();

            expect(controller.newSMS).toEqual({
                destinationFk: ticket.clientFk,
                destination: ticket.address.mobile,
                ticketId: 16
            });
        });
    });

    describe('hasDocuware()', () => {
        it('should call hasDocuware method', () => {
            $httpBackend.whenPOST(`Docuwares/${ticket.id}/checkFile`).respond(true);
            controller.hasDocuware();
            $httpBackend.flush();

            expect(controller.hasDocuwareFile).toBe(true);
        });
    });

    describe('uploadDocuware()', () => {
        it('should open dialog if not force', () => {
            controller.$.pdfToTablet = {show: () => {}};
            jest.spyOn(controller.$.pdfToTablet, 'show');
            controller.uploadDocuware(false);

            expect(controller.$.pdfToTablet.show).toHaveBeenCalled();
        });

        it('should make a query', () => {
            controller.$.balanceCreate = {show: () => {}};
            jest.spyOn(controller.vnApp, 'showSuccess');

            $httpBackend.whenPOST(`Docuwares/upload`).respond(true);
            controller.uploadDocuware(true);
            $httpBackend.flush();

            expect(controller.vnApp.showSuccess).toHaveBeenCalled();
        });
    });
});