#!/usr/bin/env python

import json
import subprocess
import sys, os

from pathlib import Path
home = str(Path.home())

lokfile = home + "/.config/waybar/location"

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib, Gdk

class EntryWindow(Gtk.Window):
    def __init__(self):
        super().__init__(title="Hava Durumu Şehri")
        self.set_size_request(200, 100)

        self.timeout_id = None

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        self.add(vbox)

        self.entry = Gtk.Entry()

        sehir = ""
        with open(lokfile,"r") as f:
          sehir = f.read().strip()

        self.entry.set_text(sehir)
        vbox.pack_start(self.entry, True, True, 0)

        button = Gtk.Button.new_with_label("Değiştir")
        button.connect("clicked", self.duzenle)
        self.entry.connect("key-press-event",self.key_press)
        vbox.pack_start(button, True, True, 0)

    def sehir_ayarla(self,sehir):
      with open(lokfile,"w") as f:
        f.write(sehir)
        sys.exit()

    def duzenle(self, button):
        sehir = self.entry.get_text()
        self.sehir_ayarla(sehir)

    def key_press(self, widget, event):
        key_name = Gdk.keyval_name(event.keyval)
        if key_name == "Return":
          sehir = self.entry.get_text()
          self.sehir_ayarla(sehir)

if len(sys.argv) > 1 and sys.argv[1] == "--girdi":
  win = EntryWindow()
  #win.connect("destroy", Gtk.main_quit)
  win.connect("delete-event", Gtk.main_quit)
  win.show_all()
  Gtk.main()
  sys.exit()

WEATHER_CODES = {
    '113': '',
    '116': '',
    '119': '',
    '122': '️',
    '143': '',
    '176': '',
    '179': '',
    '182': '',
    '185': '',
    '200': '',
    '227': '',
    '230': '',
    '248': '',
    '260': '',
    '263': '',
    '266': '',
    '281': '',
    '284': '',
    '293': '',
    '296': '',
    '299': '',
    '302': '',
    '305': '',
    '308': '',
    '311': '',
    '314': '',
    '317': '',
    '320': '',
    '323': '',
    '326': '',
    '329': '️',
    '332': '',
    '335': '️',
    '338': '',
    '350': '',
    '353': '',
    '356': '',
    '359': '',
    '362': '',
    '365': '',
    '368': '',
    '371': '️️',
    '374': '',
    '377': '',
    '386': '',
    '389': '',
    '392': '',
    '395': '️'
}

location = "Istanbul"

with open(lokfile,"r") as f:
    location = f.read().strip()

komut = "curl -s https://tr.wttr.in/{}?format=j1".format(location)

#print("-",komut)

result = subprocess.check_output(komut, shell=True).strip()
data={}

try:
  weather = json.loads(result)

  temp = weather["current_condition"][0]["temp_C"]
  code = weather["current_condition"][0]["weatherCode"]
  stat = weather["current_condition"][0]["lang_tr"][0]["value"]

  data["text"] = "{} {}°C".format(WEATHER_CODES[code], temp)
except:
  data["text"] = "error"

data["tooltip"] = location

print(json.dumps(data))
