#!/usr/bin/env python3
#
# Copyright (C) 2022 Denis 'GNUtoo' Carikli <GNUtoo@cyberdimension.org>
#
# This file is part of gnutoo-i3-sway-config.
#
# gnutoo-i3-sway-config is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3 of
# the License, or (at your option) any later version.
#
# It is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

import datetime
import os
import json
from sh import sensors

class Date(object):
    def __init__(self):
        self.date = datetime.datetime.now()
    def __str__(self):
        return "{} {:02}/{:02}/{:02} {:02}:{:02}".format(self.date.strftime("%A"),
                                                         self.date.day,
                                                         self.date.month,
                                                         self.date.year,
                                                         self.date.hour,
                                                         self.date.minute)

class Battery(object):
    def __init__(self):
        self.capacity = "/sys/class/power_supply/BAT0/capacity"
        self.status = "/sys/class/power_supply/BAT0/status"

        # Battery information
        self.energy_full_design = "/sys/class/power_supply/BAT0/energy_full_design"
        self.energy_full = "/sys/class/power_supply/BAT0/energy_full"

        # Battery identification
        self.model_name = "/sys/class/power_supply/BAT0/model_name"
        self.manufacturer = "/sys/class/power_supply/BAT0/manufacturer"
        self.serial_number = "/sys/class/power_supply/BAT0/serial_number"
        self.technology = "/sys/class/power_supply/BAT0/technology"

    def get_sysfs(self, file_path):
        if os.path.exists(file_path):
            fd = open(file_path, 'r')
            return fd.read(-1).replace('\n', '')
        else:
            return None

    def __str__(self):
        capacity = self.get_sysfs(self.capacity)
        if capacity != None:
            sign = " "
            status = self.get_sysfs(self.status)
            if status == "Charging":
                sign = "+"
            elif status == "Discharging":
                sign = "-"
            return "[ {}{} ]".format(capacity, sign)
        else:
            return "[ NA ]"

class Hwmon(object):
    def __init__(self):
        self.debug = False
    def __str__(self):
        smallest_margin = None
        output = json.loads(str(sensors('-j', '-A')))
        for hwmon, hwmon_data in output.items():
            for sensor_name, sensor_data in hwmon_data.items():
                temp_max = None
                last_temp = None
                for sysfs_name, sysfs_data in sensor_data.items():
                    if self.debug:
                        print("{} {} {}".format(sensor_name, sysfs_name, sysfs_data))
                    delim = sysfs_name.find('_')
                    sysfs_label = sysfs_name[:delim]
                    sysfs_type = sysfs_name[delim + 1:]
                    if sysfs_label.startswith('temp'):
                        if sysfs_type in ['crit', 'crit_alarm', 'max']:
                            if sysfs_data != 0:
                                if temp_max == None or temp_max > sysfs_data:
                                    temp_max = sysfs_data
                        elif sysfs_type in ['input']:
                            last_temp = sysfs_data
                if self.debug:
                    print("-> {}: {} / {}".format(sensor_name, last_temp, temp_max))
                if None not in [last_temp, temp_max]:
                    if smallest_margin == None or smallest_margin > (temp_max - last_temp):
                        smallest_margin = temp_max - last_temp
                    if self.debug:
                        print("=> {}".format(temp_max - last_temp))
        if self.debug:
            print("==> {}".format(smallest_margin))

        return "[ -{}° ]".format(smallest_margin)

if __name__ == '__main__':
    battery = Battery()
    date = Date()
    # hwmon = Hwmon()
    hwmon = ""
    print("{} {} {}".format(date, battery, hwmon))
