from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import BooleanProperty, ListProperty, StringProperty
import math
import sys
import os

def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS  # وقتی exe اجرا میشه
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

KV = '''
<Calculator>:
    orientation: 'vertical'
    padding: 10
    spacing: 10

    canvas.before:
        Color:
            rgba: (1, 1, 1, 1)
        Rectangle:
            pos: self.pos
            size: self.size
            source: root.background_image
        Color:
            rgba: (0.1, 0.1, 0.1, 0.7) if root.dark_mode else (1, 1, 1, 0.7)
        Rectangle:
            pos: self.pos
            size: self.size

    BoxLayout:
        size_hint_y: 0.1
        spacing: 10
        Button:
            text: 'dark/light'
            on_press: root.switch_theme()
        Button:
            text: 'History'
            on_press: root.show_history()
        Button:
            text: 'Clear'
            on_press: root.clear()

    TextInput:
        id: result
        font_size: 36
        size_hint_y: 0.2
        halign: 'right'
        readonly: True
        background_color: (0.2, 0.2, 0.2, 0.8) if root.dark_mode else (0.95, 0.95, 0.95, 0.8)
        foreground_color: (1, 1, 1, 1) if root.dark_mode else (0, 0, 0, 1)

    GridLayout:
        cols: 4
        spacing: 8
        rows: 6

        Button:
            text: '7'
            on_press: root.add_number('7')
        Button:
            text: '8'
            on_press: root.add_number('8')
        Button:
            text: '9'
            on_press: root.add_number('9')
        Button:
            text: '/'
            on_press: root.add_operator('/')

        Button:
            text: '4'
            on_press: root.add_number('4')
        Button:
            text: '5'
            on_press: root.add_number('5')
        Button:
            text: '6'
            on_press: root.add_number('6')
        Button:
            text: '*'
            on_press: root.add_operator('*')

        Button:
            text: '1'
            on_press: root.add_number('1')
        Button:
            text: '2'
            on_press: root.add_number('2')
        Button:
            text: '3'
            on_press: root.add_number('3')
        Button:
            text: '-'
            on_press: root.add_operator('-')

        Button:
            text: '0'
            on_press: root.add_number('0')
        Button:
            text: '.'
            on_press: root.add_number('.')
        Button:
            text: '='
            on_press: root.calculate()
        Button:
            text: '+'
            on_press: root.add_operator('+')

        Button:
            text: '('
            on_press: root.add_number('(')
        Button:
            text: ')'
            on_press: root.add_number(')')
        Button:
            text: '^'
            on_press: root.add_operator('^')
        Button:
            text: 'radical'
            on_press: root.sqrt_current()

        Button:
            text: 'sin'
            on_press: root.apply_func('sin')
        Button:
            text: 'cos'
            on_press: root.apply_func('cos')
        Button:
            text: 'tan'
            on_press: root.apply_func('tan')
        Button:
            text: 'log'
            on_press: root.apply_func('log')
'''

class Calculator(BoxLayout):
    dark_mode = BooleanProperty(True)
    history = ListProperty([])
    background_image = StringProperty('')  # مسیر تصویر پس‌زمینه

    def __init__(self, **kwargs):
        super(Calculator, self).__init__(**kwargs)
        self.background_image = resource_path('background.jpg')

    def switch_theme(self):
        self.dark_mode = not self.dark_mode

    def add_number(self, value):
        self.ids.result.text += value

    def add_operator(self, operator):
        if operator == '^':
            self.ids.result.text += '**'
        else:
            self.ids.result.text += operator

    def clear(self):
        self.ids.result.text = ''

    def calculate(self):
        try:
            result = str(eval(self.ids.result.text))
            self.history.append(self.ids.result.text + " = " + result)
            self.ids.result.text = result
        except:
            self.ids.result.text = "Error"

    def sqrt_current(self):
        try:
            expr = self.ids.result.text
            result = str(math.sqrt(eval(expr)))
            self.history.append(f"sqrt({expr}) = {result}")
            self.ids.result.text = result
        except:
            self.ids.result.text = "Error"

    def apply_func(self, func):
        try:
            expr = self.ids.result.text
            val = eval(expr)
            if func == 'sin':
                result = math.sin(math.radians(val))
            elif func == 'cos':
                result = math.cos(math.radians(val))
            elif func == 'tan':
                result = math.tan(math.radians(val))
            elif func == 'log':
                result = math.log10(val)
            else:
                result = "Error"
            self.history.append(f"{func}({expr}) = {result}")
            self.ids.result.text = str(result)
        except:
            self.ids.result.text = "Error"

    def show_history(self):
        if self.history:
            self.ids.result.text = self.history[-1]
        else:
            self.ids.result.text = "No history"

class CalculatorApp(App):
    def build(self):
        Builder.load_string(KV)
        return Calculator()

if __name__ == '__main__':
    CalculatorApp().run()
