'use strict';

var linhas = 0;

chrome.runtime.onInstalled.addListener(function (details) {
    if (details.reason == "install") {
        chrome.tabs.create({url: 'options.html'});
    }

    chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
        chrome.declarativeContent.onPageChanged.addRules([{
                conditions: [
                    new chrome.declarativeContent.PageStateMatcher({
                        pageUrl: {hostEquals: 'apj10.ifap.pt'},
                    })
                ],
                actions: [new chrome.declarativeContent.ShowPageAction()]
            }]);
    });
});

chrome.webNavigation.onCompleted.addListener(function (obj) {
    console.log('navigation');

    chrome.storage.local.get(['linhas', 'tipo', 'preenche'], function (data) {
        console.log(data.tipo);

        if (data.tipo == 'nasc') {
            if (data.linhas > 0) {
                chrome.storage.local.set({linhas: (data.linhas - 1)}, function () {

                });

                chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
                    function addLinha() {
                        if (document.getElementsByName('content:btAdicionar').length > 0) {
                            document.getElementsByName('content:btAdicionar')[0].click();
                        }
                    }

                    chrome.scripting.executeScript({
                        target: {tabId: tabs[0].id},
                        function: addLinha
                    }, function (result) {

                    });
                });
            }

            chrome.storage.local.get('preenche', function (dt) {
                if (dt.preenche == 1 && data.linhas == 0) {
                    chrome.storage.local.set({preenche: 0}, function () {});

                    let plat = '',
                        user = '',
                        pass = '',
                        data_min = '',
                        nprocessado = '',
                        nascimentos = '',
                        tipo = '';

                    chrome.storage.sync.get([
                        'plataforma',
                        'username',
                        'password',
                        'data_min',
                        'nprocessado',
                        'tipo'
                    ], function (data) {
                        plat = data.plataforma;
                        user = data.username;
                        pass = data.password;
                        data_min = data.data_min;
                        nprocessado = data.nprocessado;
                        tipo = data.tipo;
                    });

                    chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
                        function addLinha() {
                            chrome.storage.local.get('nascimentos', function (data) {
                                nascimentos = data.nascimentos;
                                nascimentos = JSON.parse(nascimentos);
                                nascimentos.forEach(function (nasc, i) {
                                    document.getElementsByName('content:idListaAnimais:' + i + ':numBri')[0].value = nasc.n_sia;
                                    document.getElementsByName('content:idListaAnimais:' + i + ':numBri')[0].dispatchEvent(new Event('change'));
                                    document.getElementsByName('content:idListaAnimais:' + i + ':datNas')[0].value = nasc.data_nasc;
                                    document.getElementsByName('content:idListaAnimais:' + i + ':datApl')[0].value = nasc.data_identif;
                                    document.getElementsByName('content:idListaAnimais:' + i + ':idPart')[0].value = nasc.casa;
                                    document.getElementsByName('content:idListaAnimais:' + i + ':briMae')[0].value = nasc.n_mae;
                                    document.getElementsByName('content:idListaAnimais:' + i + ':briPai')[0].value = nasc.n_pai;
                                    document.getElementsByName('content:idListaAnimais:' + i + ':nbaSexo')[0].value = nasc.sexo;
                                    document.getElementsByName('content:idListaAnimais:' + i + ':raca')[0].value = nasc.raca;
                                    if ('IA' == nasc.benef) {
                                        document.getElementsByName('content:idListaAnimais:' + i + ':insArt')[0].checked = true;
                                    } else if ('TE' == nasc.benef) {
                                        document.getElementsByName('content:idListaAnimais:' + i + ':traEmb')[0].checked = true;
                                        document.getElementsByName('content:idListaAnimais:' + i + ':traEmb')[0].dispatchEvent(new Event('change'));
                                        window.setTimeout(function () {
                                            document.getElementsByName('content:idListaAnimais:' + i + ':briMaeDad')[0].value = nasc.dadora;
                                        }, 2000);
                                    }
                                    if (document.getElementsByName('content:idListaAnimais:' + i + ':raca')[0].value != nasc.raca) {
                                        document.getElementsByName('content:idListaAnimais:' + i + ':raca')[0].value = nasc.cod_raca_ind;
                                        document.getElementsByName('content:idListaAnimais:' + i + ':raca')[0].dispatchEvent(new Event('change'));
                                        window.setTimeout(function () {
                                            document.getElementsByName('content:idListaAnimais:' + i + ':indRacEsp')[0].checked = true;
                                            document.getElementsByName('content:idListaAnimais:' + i + ':indRacEsp')[0].dispatchEvent(new Event('click'));
                                            window.setTimeout(function () {
                                                document.getElementsByName('content:idListaAnimais:' + i + ':racEsp')[0].value = nasc.raca;
                                            }, 2000);
                                        }, 2000);
                                    } else {
                                        document.getElementsByName('content:idListaAnimais:' + i + ':raca')[0].dispatchEvent(new Event('change'));
                                    }
                                    document.getElementsByName('content:idListaAnimais:' + i + ':codCor')[0].value = nasc.cor;
                                    document.getElementsByName('content:idListaAnimais:' + i + ':codParto')[0].value = nasc.tipo_parto;
                                    document.getElementsByName('content:idListaAnimais:' + i + ':codNascimento')[0].value = nasc.tipo_nasc;
                                });

                                chrome.storage.local.set({nascimentos: 0}, function () {});
                            });
                        }

                        chrome.scripting.executeScript({
                            target: {tabId: tabs[0].id},
                            function: addLinha
                        }, function (result) {

                        });

                    });
                }
            });

        } else if (data.tipo == 'saida') {
            chrome.tabs.query({active: true, currentWindow: true}, function (tabss) {
                function addLinha() {
                    var ret = 0;

                    if (document.getElementById('content:toolbar:editar') !== null && document.getElementById('content:pesquisasInput') !== null && document.getElementById('content:pesquisasInput').disabled) {
                        document.getElementById('content:toolbar:editar').click();
                        ret = 1;

                    } else if (document.getElementById('content:pesquisasInput') !== null && !document.getElementById('content:pesquisasInput').disabled) {
                        ret = 2;
                    }

                    return ret;
                }

                if (data.preenche > 0) {
                    chrome.scripting.executeScript({
                        target: {tabId: tabss[0].id},
                        function: addLinha
                    }, function (result) {
                        if (result[0].result == 2) {
                            chrome.storage.local.get('saidas', function (s) {
                                let saidas = JSON.parse(s.saidas);

                                if (saidas.length > 0) {
                                    function addAnimais() {
                                        //document.getElementById('content:rbtnIdeMac:0').click();
                                        console.log('get_saidas');

                                        chrome.storage.local.get('saidas', function (s) {
                                            var pag = 1;
                                            let saidas = JSON.parse(s.saidas);

                                            processaPagina();

                                            function processaPagina() {
                                                console.log('processaPagina saida');

                                                let pagina = document.getElementById('content:idListaAnimais_data').children;

                                                for (let linha of pagina) {
                                                    let key = saidas.indexOf(linha.children[0].textContent.trim());

                                                    if (key > -1) {
                                                        //linha.lastElementChild.firstElementChild.firstElementChild.checked = true;
                                                        linha.children[linha.children.length - 2].firstElementChild.firstElementChild.checked=true;

                                                        chrome.runtime.sendMessage({
                                                            contador: 1,
                                                            sia: saidas[key]
                                                        });

                                                        saidas.splice(key, 1);
                                                    }
                                                }

                                                if (!document.getElementById('content:idListaAnimais_paginator_bottom').lastElementChild.classList.contains('ui-state-disabled')) {
                                                    document.getElementById('content:pesquisasInput').dispatchEvent(new Event('change'));

                                                    window.setTimeout(function () {
                                                        let len = document.getElementById('content:idListaAnimais_paginator_bottom').children.length - 1;
                                                        document.getElementById('content:idListaAnimais_paginator_bottom').children[len].click();

                                                    }, 1000);

                                                    window.setTimeout(function () {
                                                        processaPagina();

                                                    }, 2000);

                                                } else {
                                                    console.log('done!');

                                                    document.getElementById('content:pesquisasInput').dispatchEvent(new Event('change'));

                                                    chrome.storage.local.set(
                                                        {
                                                            linhas: 0,
                                                            preenche: 0,
                                                            saidas: JSON.stringify(saidas)
                                                        },
                                                        function () {
                                                            for (let sia of saidas) {
                                                                chrome.runtime.sendMessage({
                                                                    contador: -1,
                                                                    sia: sia
                                                                });
                                                            }
                                                        }
                                                    );
                                                }
                                            }
                                        });
                                    }

                                    chrome.scripting.executeScript({
                                        target: {tabId: tabss[0].id},
                                        function: addAnimais
                                    }, function (res) {

                                    });
                                }
                            });
                        }
                    });
                }
            });
        } else if (data.tipo == 'saida_oc') {
            chrome.tabs.query({active: true, currentWindow: true}, function (tabss) {
                function addLinha() {
                    var ret = 0;

                    if (document.getElementById('content:toolbar:editar') !== null && document.getElementById('content:pesquisasInput') !== null && document.getElementById('content:pesquisasInput').disabled) {
                        document.getElementById('content:toolbar:editar').click();
                        ret = 1;
                        
                    } else if (document.getElementById('content:pesquisasInput') !== null && !document.getElementById('content:pesquisasInput').disabled) {
                        ret = 2;
                    }

                    return ret;
                }

                if (data.preenche > 0) {
                    chrome.scripting.executeScript({
                        target: {tabId: tabss[0].id},
                        function: addLinha
                    }, function (result) {
                        if (result[0].result == 2) {
                            chrome.storage.local.get('saidas', function (s) {
                                let saidas = JSON.parse(s.saidas);

                                if (saidas.length > 0) {
                                    function addAnimais() {
                                        document.getElementById('content:rbtnIdeMac:0').click();
                                        console.log('get_saidas');

                                        chrome.storage.local.get('saidas', function (s) {
                                            var pag = 1;
                                            let saidas = JSON.parse(s.saidas);

                                            processaPagina();

                                            function processaPagina() {
                                                console.log('processaPagina saida_oc');

                                                let pagina = document.getElementById('content:idListaAnimais_data').children;

                                                for (let linha of pagina) {
                                                    let key = saidas.indexOf(linha.children[1].textContent.trim());
                                                    if (key > -1) {
                                                        linha.lastElementChild.firstElementChild.firstElementChild.checked = true;
                                                        chrome.runtime.sendMessage({
                                                            contador: 1,
                                                            sia: saidas[key]
                                                        });
                                                        saidas.splice(key, 1);
                                                    }
                                                }

                                                if (!document.getElementById('content:idListaAnimais_paginator_bottom').lastElementChild.classList.contains('ui-state-disabled')) {
                                                    document.getElementById('content:pesquisasInput').dispatchEvent(new Event('change'));

                                                    window.setTimeout(function () {
                                                        let len = document.getElementById('content:idListaAnimais_paginator_bottom').children.length - 1;
                                                        document.getElementById('content:idListaAnimais_paginator_bottom').children[len].click();
                                                    }, 1000);

                                                    window.setTimeout(function () {
                                                        processaPagina();
                                                    }, 2000);

                                                } else {
                                                    console.log('done!');
                                                    document.getElementById('content:pesquisasInput').dispatchEvent(new Event('change'));
                                                    chrome.storage.local.set({
                                                        linhas: 0,
                                                        preenche: 0,
                                                        saidas: JSON.stringify(saidas)
                                                    },
                                                            function () {
                                                                for (let sia of saidas) {
                                                                    chrome.runtime.sendMessage({
                                                                        contador: -1,
                                                                        sia: sia
                                                                    });
                                                                }
                                                            });
                                                }
                                            }
                                        });
                                    }

                                    chrome.scripting.executeScript({
                                        target: {tabId: tabss[0].id},
                                        function: addAnimais
                                    }, function (res) {

                                    });
                                }
                            });
                        }
                    });
                }
            });
        }
    });
});