import { tsx } from "@arcgis/core/widgets/support/widget.js" assert { type:'json'};
import { property, subclass } from "@arcgis/core/core/accessorSupport/decorators.js" assert { type:'json'};
import Widget from "@arcgis/core/widgets/Widget.js" assert { type:'json'};
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils";
import WeatherWidgetViewModel, { IWeatherWidgetParameters } from "./view-model/widgetViewModel";

//create an interface for our expected parameters
interface WeatherParams extends __esri.WidgetProperties, IWeatherWidgetParameters {
    view: __esri.MapView | __esri.SceneView | undefined;
}

//subtype from esri.widgets
@subclass("esri.widgets.WeatherWidget")
export default class WeatherWidget extends Widget {


    @property()
    view: __esri.MapView | __esri.SceneView | undefined;
        
    @property()
    WeatherWidgetVM: WeatherWidgetViewModel;

    //Create an array to hold any handles we create
    viewHandles: Array<IHandle>;

    constructor(params?: WeatherParams) {
        super(params);
        //assign the view
        this.view = params?.view;
        this.viewHandles = [];
        //create the new view model
        this.WeatherWidgetVM = new WeatherWidgetViewModel({ weatherAPI: params?.weatherAPI, weatherURL: params?.weatherURL, view: this.view });
      
    }
    //lifecycle method
    // Needed modifications because watchUtils is deprecated in 4.28:
    // https://www.esri.com/arcgis-blog/products/js-api-arcgis/developers/reactiveutils-and-why-you-should-be-using-them-instead-of-watchutils-with-the-arcgis-maps-sdk-for-javascript/
    postInitialize() {
        //if we have a view, set up a watch for when the view is stationary.
        //using watchUtils as this needs to be compatible for ExB which uses JSAPI 4.23
        //At the next version we should use reactiveUtils which is only available at JSAPI 4.24
        if (this.view) {
            const whenHandle = reactiveUtils.watch(
                // this.view, "stationary",
                () => this.view?.updating,
                (updating) => {
                    console.log(updating);
                    //when we stop moving, call update extent
                    this.updateViewExtent();
                });
            //assign the handle
            this.own(whenHandle);
            //push the handle in to the array so we can destroy it
            this.viewHandles.push(whenHandle);
            if (this.view) {
                //get the latest weather for the location.
                this.getCurrentWeather(this.view?.extent.center);
            }
        }
    }

    //when the extent has updated, get the latest weather
    updateViewExtent = () => {
        console.log("View updated two");
        if (this.view !== undefined) {
            console.log("Getting weather");
            this.getCurrentWeather(this.view.extent.center);
        }
    }

    //get the lates weather from the view model.
    getCurrentWeather = (point: __esri.Point) => {
        console.log("Getting latest data")
        this.WeatherWidgetVM.getLatestWeather(point.latitude, point.longitude).then((result) => {
            console.log("Latest weather");
            if (result === true) {
                console.log("Rendering");               
                this.renderNow();
            }
        });
    }

    //lifecycle method, remove any watch handles
    destroy() {
        for (let h of this.viewHandles) {
            h.remove();
        }
        this.viewHandles.length = 0;
    }
    
    //lifecycle method, renders the view.
    render() {
        console.log("Render Called");
        if (this.WeatherWidgetVM === undefined || this.WeatherWidgetVM.currentWeather === undefined) {
            return <div id="idPanelLoad" class="loader is-active padding-leader-3 padding-trailer-3">
                <div id="loading-bars" class="loader-bars"></div>
                <div id="loader-text" class="loader-text">Loading...</div>
            </div>
        }
        return (
            <div id="panel" class="panel modifier-class text-center" style="width:250px">
                <div class="trailer font-size--2" id="lblWeatherHeader">CURRENT WEATHER</div>
                <div class="font-size-1" id="lblWeatherLocation" >{this.WeatherWidgetVM.currentWeather.location.name}</div>
                <div class="font-size--1" id="lblWeatherCountry" >{this.WeatherWidgetVM.currentWeather.location.country}</div>
                
                <div class="font-size-5" id="lblWeatherTempC" >{this.WeatherWidgetVM.currentWeather.current.temp_c}&#176;</div>

                <div class="font-size-1" id="lblWeatherLocalConditionTest" >{this.WeatherWidgetVM.currentWeather.current.condition.text}</div>
                <div class="font-size--1" id="lblWeatherFeelsLikeC" >Feels like {this.WeatherWidgetVM.currentWeather.current.feelslike_c}&#176;</div>
                <div class="font-size--1" id="lblWeatherPrecipMM" >min: {this.WeatherWidgetVM.currentWeather.forecast.forecastday[0].day.mintemp_c}&#176; max:{this.WeatherWidgetVM.currentWeather.forecast.forecastday[0].day.maxtemp_c}&#176; </div>
                <div class="font-size--1" id="lblWeatherCloud" >Cloud cover: {this.WeatherWidgetVM.currentWeather.current.cloud}%</div>
                <div class="font-size--1" id="lblWeatherPrecipMM" >Rainfall: {this.WeatherWidgetVM.currentWeather.current.precip_mm}mm</div>

                <div id="linkBack">
                    Powered by <a href="https://www.weatherapi.com/" title="Free Weather API">WeatherAPI.com</a>
                </div>
            </div>

        )
    }
}
