<?php

namespace Ecomnova;

use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\WebDriverSelect;

class ProductPageAppleyardDesktop extends EcomnovaPage implements ProductPageInterface
{
    public function __construct()
    {
        parent::__construct();
    }
    public function selectSizeOptionByLabel($label): \Facebook\WebDriver\Remote\RemoteWebElement
    {
        $label = $this->driver->findElement(WebDriverBy::xpath($this->getLabelXpath($label)));
        $parent = $this->getParentElement($this->getParentElement($label));
        $radioButton = $this->findFirstRadioButton($parent);
        $radioButton->click();
        return $radioButton;
    }
    public function getTotalPrice()
    {
        //find div with class price-box and then inside div with class price get the text
        $prices = $this->driver->findElements(WebDriverBy::cssSelector('.price-box .price'));
        $lastPrice = end($prices);
        return $lastPrice->getText();
    }


    public function selectGiftOptionByLabel(string $giftLabel)
    {
        $giftOption = $this->driver->findElement(WebDriverBy::xpath($this->getLabelXpath($giftLabel)));
        $parent = $this->getParentElement($this->getParentElement($giftOption));
        $checkbox = $this->findFirstCheckbox($parent);
        $checkbox->click();
        return $checkbox;
    }

    public function enterRecipientName($name)
    {
        $recipientName = $this->driver->findElement(WebDriverBy::cssSelector('.formtrack-product-recipientname'));
        $recipientName->sendKeys($name);
        return $recipientName;
    }

    public function enterPersonalMessage($message)
    {
        $personalMessage = $this->driver->findElement(WebDriverBy::cssSelector('.formtrack-product-giftmessage'));
        $personalMessage->sendKeys($message);
        return $personalMessage;
    }
    public function selectGiftCardByLabel(string $label)
    {
        $radioButton = $this->driver->findElement(WebDriverBy::xpath($this->getLabelXpath($label)));
        $parent = $this->getParentElement($this->getParentElement($radioButton));
        $radioButton = $this->findFirstRadioButton($parent);
        $radioButton->click();
        return $radioButton;
    }

    public function selectRecipientAddress($postcode, $addressLineNumber = 1)
    {
        $postcodeTextBox = $this->driver->findElement(WebDriverBy::cssSelector('.formtrack-product-deliverypostcode'));
        $postcodeTextBox->sendKeys($postcode);
        $this->driver->findElement(WebDriverBy::id('product_page_find_address_btn'))->click();
        $this->driver->wait(10)->until(
            WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::id('crafty_postcode_lookup_result_option1'))
        );
        //from the select id  crafty_postcode_lookup_result_option1 select the first option
        $select = $this->driver->findElement(WebDriverBy::id('crafty_postcode_lookup_result_option1'));
        $select = new WebDriverSelect($select);
        $select->selectByIndex($addressLineNumber);
        return $this->getAddressFields();
    }

    public function getAddressFields()
    {
        $companyName = $this->driver->findElement(WebDriverBy::id('company_id'));
        $addressLine1 = $this->driver->findElement(WebDriverBy::id('street1_id'));
        $addressLine2 = $this->driver->findElement(WebDriverBy::id('street2_id'));
        $town = $this->driver->findElement(WebDriverBy::id('town_id'));
        $county = $this->driver->findElement(WebDriverBy::id('county_id'));
        return [
            'companyName' => $companyName->getAttribute('value'),
            'addressLine1' => $addressLine1->getAttribute('value'),
            'addressLine2' => $addressLine2->getAttribute('value'),
            'town' => $town->getAttribute('value'),
            'county' => $county->getAttribute('value')
        ];
    }

    public function selectDeliveryDate($dateDay = 0)
    {
        /*$imageElement = $this->driver->findElement(WebDriverBy::xpath("//img[@alt='Select Date']"));
        $imageElement->click();*/
        $deliveryDate = $this->driver->findElement(WebDriverBy::cssSelector('.datetime-picker'))->click();
        //wait for element with class calendar to be visible
        $this->driver->wait(10)->until(
            WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::cssSelector('.calendar'))
        );
        if(is_int($dateDay) && $dateDay > 0){
            $firstAvailableDate = $this->driver->findElement(WebDriverBy::xpath("//td[contains(text(),'$dateDay')]"));
        }else{
            $firstAvailableDate = $this->driver->findElement(WebDriverBy::cssSelector('.day.selected'));
        }
        $firstAvailableDate->click();
        return $deliveryDate;
    }

    public function selectPrivilegeOption()
    {
        $privilegeOption = $this->getPrivilegeOption();
        if(!$privilegeOption->isSelected()){
            $privilegeOption->click();
        }
        return $privilegeOption;
    }

    public function unselectPrivilegeOption()
    {
        $privilegeOption = $this->getPrivilegeOption();
        if($privilegeOption->isSelected()){
            $privilegeOption->click();
        }
        return $privilegeOption;
    }

    public function selectDeliveryMethodByName($method = null)
    {
        //if method is not null, find a label with the text of the method and click it
        if($method !== null){
            $deliveryMethod = $this->getLabelXpath($method);
            $this->driver->findElement(WebDriverBy::xpath($deliveryMethod))->click();
            $parent = $this->getParentElement($this->getParentElement(
                $this->driver->findElement(WebDriverBy::xpath($deliveryMethod)
                )));
            return $this->findFirstRadioButton($parent, true);
        }
        $deliveryMethods = $this->driver->findElement(WebDriverBy::cssSelector('.formtrack-product-deliverymethod'));
        return $deliveryMethods->findElement(WebDriverBy::cssSelector('input[type="radio"]:checked'));
    }

    public function getBasePrice() : string
    {
        try {
            $this->driver->wait()->until(
                WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::id('titlePrice'))
            );
            return $this->driver->findElement(WebDriverBy::id('titlePrice'))->getText();
        }catch (\Exception $e) {
            throw new \Exception("Element with selector 'titlePrice' not found within 30 seconds. ".$e->getMessage());
        }
    }

    public function selectOccasionOptionByName($occasion)
    {
        // TODO: Implement selectSpecialInstructionByName() method.
        $occasionOption = $this->driver->findElement(WebDriverBy::cssSelector('.sc-formtrack-product-occasion'));
        // find ul element with class .chosen-results

        $resultsUl = $occasionOption->findElement(WebDriverBy::cssSelector('.chosen-results'));

        var_dump($resultsUl->getDomProperty('outerHTML'));


        var_dump($occasionOption->getDomProperty('innerHTML'));
        return $occasionOption;
    }

    public function selectSpecialInstructionByName($instruction)
    {
        // TODO: Implement selectSpecialInstructionByName() method.
    }

    public function enterRecipientAddress(AddressFields $addressFields)
    {
        // TODO: Implement enterRecipientAddress() method.
    }

    public function addToCart(string $label)
    {
        // TODO: Implement addToCart() method.
    }


    private function getPrivilegeOption()
    {
        return $this->driver->findElement(WebDriverBy::cssSelector('.formtrack-product-join-appleyard-privilege_PRIV12M'));
    }
}