#!/usr/bin/env python3

# Copyright 2021-2023 Ian Jauslin
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.config import Config
import sys
import os.path

from painter import Painter
from status_bar import Status_bar
from command_prompt import Command_prompt
import filecheck

# App class
class Jam_app(App):
    # name of .kv file for main interface
    kv_file="jam.kv"

    def __init__(self,**kwargs):
        # the file open for editing
        self.openfile=kwargs.get("openfile","")

        # readonly mode
        self.readonly=False

        super(Jam_app,self).__init__()


    def build(self):
        layout=BoxLayout(orientation="vertical")

        # painter
        self.painter=Painter(self)
        # status bar
        self.status_bar=Status_bar(self)
        # command prompt
        self.command_prompt=Command_prompt(self)

        layout.add_widget(self.painter)
        layout.add_widget(self.status_bar)
        layout.add_widget(self.command_prompt)

        # read openfile
        if os.path.isfile(self.openfile):
            # read the file
            self.painter.read(self.openfile)
            # set readonly mode
            self.readonly=not os.access(self.openfile,os.W_OK)

        return layout


# disable red circles on right click
Config.set('input', 'mouse', 'mouse,disable_multitouch')
# do not exit on escape
Config.set('kivy', 'exit_on_escape', 0)

# read cli
openfile=""
if len(sys.argv)==2:
    openfile=sys.argv[1]
    # check file
    (ret,message)=filecheck.check_edit(openfile)
    if ret<0:
        print(message,file=sys.stderr)
        exit(-1)

# run
if __name__ == '__main__':
    Jam_app(openfile=openfile).run()
