import unittest

import mockredis
from splinter import Browser

from helix import main
from helix.constants import redis_constant
from helix.constants import sql_constant
from helix.constants.anchor_type import AnchorType
from helix.constants.inverter_type import InverterType
from helix.constants.module_type import ModuleType
from helix.constants.system_type import SystemType
from helix.models.sql.power_stations import PowerStation
from test.integration.integration_test_helpers import *
from test.test_helpers import assert_error, test_db_session, assert_no_error, \
    reset_db_session


class PowerStationConfigurationTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.test_db_session = test_db_session()

    @classmethod
    def tearDownClass(cls):
        cls.test_db_session.close_all()

    def setUp(self):
        redis_constant.redis_store = mockredis.mock_redis_client()
        sql_constant.sql_session_maker = lambda: self.test_db_session

        self.app = main.app.test_client()
        self.browser = Browser('flask', app=main.app)
        self.fill_in_site_characterization_data()
        self.browser.visit('/power_station_configuration/')

    def tearDown(self):
        reset_db_session(self.test_db_session)

    def fill_in_site_characterization_data(self,
                                           system_type=SystemType.singleTilt,
                                           module_type=ModuleType.Cell96):
        self.browser.visit('/site_characterization/')
        self.browser.fill('project_name', 'Test Project Name')
        self.browser.fill('building_width', '200')
        self.browser.fill('building_height', '30')
        self.browser.fill('building_length', '75.5')
        self.browser.fill('wind_speed', '125')
        self.browser.fill('exposure_category', 'C')
        self.browser.fill('ballast_block_weight', '13')
        self.browser.fill('building_parapet_height', '0')
        self.browser.fill('max_system_pressure', '10')
        self.browser.fill('system_type', system_type.value)
        self.browser.fill('anchor_type', AnchorType.EcoFasten.value)
        self.browser.fill('module_type', module_type.value)
        self.browser.fill('design_spectral_response', '1.02')
        self.browser.find_by_value('Next').first.click()
        self.browser.visit('/power_station_configuration/')

    def test_entering_power_station_data_shows_entered_values_in_table(self):
        fill_in_power_station(self.browser, name='Test Power Station Name', inverter_count=3, inverters=[
            {
                'model': InverterType.SMA.MODEL_15KW,
                'strings': '3',
            },
            {
                'model': InverterType.SMA.MODEL_12KW,
                'strings': '4',
            },
            {
                'model': InverterType.SMA.MODEL_24KW,
                'strings': '7',
            }
        ])
        submit_power_station_form(self.browser)

        assert_number_of_power_station_table_rows(self.browser, 1)
        models = ['15kW SMA Tripower - 514687', '12kW SMA Tripower - 514686', '24kW SMA Tripower - 514685']
        strings = ['3', '4', '7']
        assert_power_station_table_row(self.browser, 1, name='Test Power Station Name', models=models, strings=strings,
                                       quantity=1)

        eq_(self.browser.find_by_name('power_station_description').first.value, 'Power Station 2')

    def test_clicking_back_goes_to_summary_table(self):
        self.browser.click_link_by_partial_text('Back')
        assert_step_is_active(self.browser, 3)

    def test_all_power_station_values_are_required(self):
        fill_in_power_station(self.browser, name='', count='', run_length='')
        submit_power_station_form(self.browser)
        assert_error(self.browser, 'power_station_description', 'Power Station Description is required.')
        assert_error(self.browser, 'power_station_quantity', 'Not a valid integer value')
        assert_error(self.browser, 'ac_run_length', 'Not a valid integer value')
        eq_(len(self.browser.find_by_css('#power_station_form.hidden')), 0)

    def test_ac_run_length_must_be_non_negative(self):
        fill_in_power_station(self.browser, run_length=-5)
        submit_power_station_form(self.browser)
        assert_error(self.browser, 'ac_run_length', 'Number must be at least 0.')
        eq_(len(self.browser.find_by_css('#power_station_form.hidden')), 0)

    def test_ac_run_length_defaults_to_zero(self):
        eq_(self.browser.find_by_name('ac_run_length').first.value, '0')

    def test_power_station_quantity_must_be_non_negative(self):
        fill_in_power_station(self.browser, count=-2)
        submit_power_station_form(self.browser)
        assert_error(self.browser, 'power_station_quantity', 'Number must be at least 0.')
        eq_(len(self.browser.find_by_css('#power_station_form.hidden')), 0)

    def test_power_station_description_defaults_to_power_station_1(self):
        eq_(self.browser.find_by_name('power_station_description').first.value, 'Power Station 1')

    def test_default_inverter_type_is_24kW(self):
        eq_(self.browser.find_by_name('inverter_1-model').first.value, str(InverterType.SMA.MODEL_24KW.value))
        eq_(self.browser.find_by_name('inverter_2-model').first.value, str(InverterType.SMA.MODEL_24KW.value))
        eq_(self.browser.find_by_name('inverter_3-model').first.value, str(InverterType.SMA.MODEL_24KW.value))
        eq_(self.browser.find_by_name('inverter_4-model').first.value, str(InverterType.SMA.MODEL_24KW.value))

    def test_clicking_trash_can_deletes_power_station(self):
        fill_in_power_station(self.browser, name='Fake PS ONE')
        submit_power_station_form(self.browser)
        fill_in_power_station(self.browser, name='Fake PS TWO')
        submit_power_station_form(self.browser)

        assert_number_of_power_station_table_rows(self.browser, 2)

        self.browser.click_link_by_partial_href('delete_power_station')

        assert_number_of_power_station_table_rows(self.browser, 1)

        assert not self.browser.is_text_present('Fake PS ONE')
        assert self.browser.is_text_present('Fake PS TWO')

        self.browser.click_link_by_partial_href('delete_power_station')
        eq_(len(self.browser.find_by_css('.power_station_table')), 0)

    def test_standalone_inverter_form_does_not_show_power_stations_with_more_than_one_in_group(self):
        fill_in_power_station(self.browser, name='Fake PS ONE', inverter_count=3, count=1)
        submit_power_station_form(self.browser)

        submit_standalone_inverter_form(self.browser)
        fill_in_power_station(self.browser, name='Fake PS TWO', inverter_count=3, count=2)
        submit_power_station_form(self.browser)

        attachment_point_options = self.browser.find_by_css('#attachment_point option')
        eq_(len(attachment_point_options), 2)
        attachment_options_as_list = list(map(lambda x: x.text, attachment_point_options))
        eq_(attachment_options_as_list, ['Switch Gear', 'Fake PS ONE'])

    def test_standalone_inverter_form_only_shows_power_stations_with_open_spots(self):
        fill_in_power_station(self.browser, name='Fake PS ONE', inverter_count=2, count=1)
        submit_power_station_form(self.browser)

        fill_in_power_station(self.browser, name='Fake PS TWO', inverter_count=4, count=1)

        submit_power_station_form(self.browser)

        attachment_point_options = self.browser.find_by_css('#attachment_point option')
        eq_(len(attachment_point_options), 2)
        attachment_options_as_list = list(map(lambda x: x.text, attachment_point_options))
        eq_(attachment_options_as_list, ['Switch Gear', 'Fake PS ONE'])

        power_station_id = str(self.test_db_session.query(PowerStation).first().id)
        self.browser.fill('attachment_point', power_station_id)
        submit_standalone_inverter_form(self.browser)

        attachment_point_options = self.browser.find_by_css('#attachment_point option')
        eq_(len(attachment_point_options), 2)
        attachment_options_as_list = list(map(lambda x: x.text, attachment_point_options))
        eq_(attachment_options_as_list, ['Switch Gear', 'Fake PS ONE'])

        self.browser.fill('attachment_point', power_station_id)
        submit_standalone_inverter_form(self.browser)

        attachment_point_options = self.browser.find_by_css('#attachment_point option')
        eq_(len(attachment_point_options), 1)
        attachment_options_as_list = list(map(lambda x: x.text, attachment_point_options))
        eq_(attachment_options_as_list, ['Switch Gear'])

    def test_standalone_inverter_quantity_creates_multiple_inverters(self):
        fill_in_standalone_inverter(self.browser, quantity=5, model=InverterType.SMA.MODEL_15KW, strings=3, sunshade=True, dc_switch=True)
        submit_standalone_inverter_form(self.browser)

        assert_number_of_standalone_inverter_table_rows(self.browser, 5)

        assert_standalone_inverter_row(self.browser, 1, model=InverterType.SMA.MODEL_15KW, strings=3, sunshade=True, dc_switch=True)
        assert_standalone_inverter_row(self.browser, 2, model=InverterType.SMA.MODEL_15KW, strings=3, sunshade=True, dc_switch=True)
        assert_standalone_inverter_row(self.browser, 3, model=InverterType.SMA.MODEL_15KW, strings=3, sunshade=True, dc_switch=True)
        assert_standalone_inverter_row(self.browser, 4, model=InverterType.SMA.MODEL_15KW, strings=3, sunshade=True, dc_switch=True)
        assert_standalone_inverter_row(self.browser, 5, model=InverterType.SMA.MODEL_15KW, strings=3, sunshade=True, dc_switch=True)

    def test_entering_standalone_inverter_data_shows_entered_values_in_table_and_hides_form(self):
        submit_standalone_inverter_form(self.browser)
        fill_in_power_station(self.browser, name='Fake PS ONE', inverter_count=3)
        submit_power_station_form(self.browser)
        fill_in_standalone_inverter(self.browser, model=InverterType.SMA.MODEL_15KW, strings=3, sunshade=True, dc_switch=True)
        power_station_id = str(self.test_db_session.query(PowerStation).first().id)
        self.browser.fill('attachment_point', power_station_id)
        submit_standalone_inverter_form(self.browser)

        assert_number_of_standalone_inverter_table_rows(self.browser, 2)
        assert_standalone_inverter_row(self.browser, 1,
                                       model=InverterType.SMA.MODEL_24KW,
                                       interconnect='Switch Gear',
                                       strings=8,
                                       dc_switch=False,
                                       sunshade=False)

        assert_standalone_inverter_row(self.browser, 2,
                                       model=InverterType.SMA.MODEL_15KW,
                                       interconnect='Fake PS ONE',
                                       strings=3,
                                       dc_switch=True,
                                       sunshade=True)

        assert len(self.browser.find_by_css('#standalone_inverter_form.hidden')) == 1

    def test_standalone_inverter_ac_run_length_must_be_non_negative(self):
        fill_in_standalone_inverter(self.browser, ac_run_length=-5)
        submit_standalone_inverter_form(self.browser)
        assert_error(self.browser, 'standalone_ac_run_length', 'Number must be at least 0.')
        eq_(len(self.browser.find_by_css('#standalone_inverter_form.hidden')), 0)

    def test_standalone_inverter_ac_run_length_defaults_to_zero(self):
        eq_(self.browser.find_by_name('standalone_ac_run_length').first.value, '0')

    def test_clicking_trash_can_deletes_standalone_inverter(self):
        eq_(len(self.browser.find_by_css('.standalone_inverter_table')), 0)

        submit_standalone_inverter_form(self.browser)

        assert_no_error(self.browser, 'attachment_point')

        assert_number_of_standalone_inverter_table_rows(self.browser, 1)

        fill_in_power_station(self.browser, name='Fake PS ONE', count=1, inverter_count=3)
        submit_power_station_form(self.browser)

        power_station_id = str(self.test_db_session.query(PowerStation).first().id)

        self.browser.fill('attachment_point', power_station_id)
        submit_standalone_inverter_form(self.browser)

        assert_number_of_standalone_inverter_table_rows(self.browser, 2)

        self.browser.click_link_by_partial_href('delete_standalone_inverter')

        assert_number_of_standalone_inverter_table_rows(self.browser, 1)

        assert_standalone_inverter_row(self.browser, 1, interconnect='Fake PS ONE')

        self.browser.click_link_by_partial_href('delete_standalone_inverter')
        eq_(len(self.browser.find_by_css('.standalone_inverter_table')), 0)

    def test_supervisor_monitoring_form_does_not_show_power_stations_that_already_have_monitoring(self):
        fill_in_power_station(self.browser, name='Fake PS One')
        submit_power_station_form(self.browser)

        power_source_options = self.browser.find_by_css('#power_source option')
        eq_(len(power_source_options), 2)
        power_source_options_as_list = list(map(lambda x: x.text, power_source_options))
        eq_(power_source_options_as_list, ['Switch Gear/External', 'Fake PS One'])

        power_station_id = str(self.test_db_session.query(PowerStation).first().id)
        fill_in_monitoring_form(self.browser, power_station_id)
        submit_monitoring_form(self.browser)

        power_source_options = self.browser.find_by_css('#power_source option')
        eq_(len(power_source_options), 1)
        power_source_options_as_list = list(map(lambda x: x.text, power_source_options))
        eq_(power_source_options_as_list, ['Switch Gear/External'])

    def test_adding_supervisor_monitoring_to_power_station_shows_monitoring_label_on_power_station_table(self):
        fill_in_power_station(self.browser, name='Fake PS One')
        submit_power_station_form(self.browser)

        power_station_id = str(self.test_db_session.query(PowerStation).first().id)

        fill_in_monitoring_form(self.browser, power_station_id)
        submit_monitoring_form(self.browser)

        row = self.browser.find_by_css('.power_station_table tr:nth-child(2) td:nth-child(1)').first
        assert "Monitoring" in row.text, "Expected \n'%s'\n to contain 'Monitoring'" % row.text

    def test_entering_supervisor_monitoring_data_shows_entered_values_in_table_and_hides_form(self):
        fill_in_monitoring_form(self.browser, 'switch_gear')
        submit_monitoring_form(self.browser)
        assert_number_of_supervisor_monitor_table_rows(self.browser, 1)
        assert_supervisor_monitor_row(self.browser, 1, 'Switch Gear/External')
        eq_(len(self.browser.find_by_css('#supervisor_monitor_form.hidden')), 1)

    def test_clicking_trash_can_deletes_supervisor_monitor(self):
        fill_in_monitoring_form(self.browser, 'switch_gear')
        submit_monitoring_form(self.browser)

        fill_in_power_station(self.browser, name='Fake PS ONE')
        submit_power_station_form(self.browser)

        power_station_id = str(self.test_db_session.query(PowerStation).first().id)
        fill_in_monitoring_form(self.browser, power_station_id)
        submit_monitoring_form(self.browser)

        assert_number_of_supervisor_monitor_table_rows(self.browser, 2)
        self.browser.click_link_by_partial_href('delete_supervisor_monitor')

        assert_number_of_supervisor_monitor_table_rows(self.browser, 1)

        assert_supervisor_monitor_row(self.browser, 1, 'Fake PS ONE')

        self.browser.click_link_by_partial_href('delete_supervisor_monitor')
        eq_(len(self.browser.find_by_css('.supervisor_monitor_table')), 0)
