#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  List System
#  Copyright (C) 2011 Øyvind Jensen
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Affero General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program 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 Affero General Public License for more details.
#
#  You should have received a copy of the GNU Affero General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

import cmd
import shelve
import os

class CLI(cmd.Cmd):


    header = 'Virtual Inventory Logger'
    prompt = '> '
    storage = None
    snd = None
    filename = 'registry'
    unablemsg = 'Unable to complete operation'

    def complete_most(self, text, line):
        col = []
        for key in self.storage.keys():
            col.append(key)
            for item in self.storage[key]:
                col.append(item)
        if text:
            return [
                key for key in col
                if key.startswith(text)
            ]
        else:
            return col

    def log(self, line):
        os.system('journal ' + line)

    def do_place(self, op):
        'USAGE: place <name> <location>'
        thinglocation = op.split()
        thinglocation = self.strip(thinglocation)
        if len(thinglocation) == 2:
            location = thinglocation[1]
            name = thinglocation[0]
            try:
                self.storage[location]
            except KeyError:
                self.storage[location] = []
            self.storage[location].append(name)
            response = name + ' placed in ' + location
            self.log(response)
        else:
            print(self.unablemsg)

    def complete_place(self, text, line, start_index, end_index):
        return self.complete_most(text, line)

    def do_search(self, phrase):
        'USAGE: search <name>'
        found = False
        if len(phrase) > 0:
            for location in self.storage:
                for item in self.storage[location]:
                    if phrase in item or item in phrase:
                        print(item + ' is located in ' + location)
                        found = True
            if not found:
                print(phrase + ' is nowhere to be found')
                print('Please get one and put it somewhere')
        else:
            print(self.unablemsg)

    def do_remove(self, op):
        'USAGE: remove <name> <location>'
        thinglocation = op.split()
        thinglocation = self.strip(thinglocation)
        if len(thinglocation) == 2:
            location = thinglocation[1]
            name = thinglocation[0]
            try:
                self.storage[location].remove(name)
                if len(self.storage[location]) == 0:
                    self.storage.pop(location)
                response = name + ' removed from ' + location
                self.log(response)
            except:
                print(name + ' not found in ' + location)
        else:
            print(self.unablemsg)

    def complete_remove(self, text, line, start_index, end_index):
        return self.complete_most(text, line)

    def do_move(self, op):
        'USAGE: move <name> <from location> <to location>'
        moveop = op.split()
        moveop = self.strip(moveop)
        if len(moveop) == 3:
            name = moveop[0]
            fromloc = moveop[1]
            toloc = moveop[2]
            self.do_remove(name + ' ' + fromloc)
            self.do_place(name + ' ' + toloc)
            #print(name + ' moved from ' + fromloc + ' to ' + toloc)
        else:
            print(self.unablemsg)

    def complete_move(self, text, line, start_index, end_index):
        return self.complete_most(text, line)

    def do_list(self, location):
        'USAGE: list <location>'
        if len(location) > 0:
            self.list_location(location)
        else:
            for onelocation in self.storage:
                self.list_location(onelocation)

    def complete_list(self, text, line, start_index, end_index):
        return self.complete_most(text, line)

    def do_journal(self, line):
        'USAGE: journal <journal entry>'
        os.system('journal ' + line)

    def strip(self, tostrip):
        words = ['in', 'from', 'inside', 'into']
        for word in words:
            if word in tostrip:
                tostrip.remove(word)
        return tostrip

    def list_location(self, location):
        print(location)
        try:
            if self.storage[location] is not None:
                for item in self.storage[location]:
                    print('\t' + item)
        except KeyError:
            print('There is no place like ' + location)

    def do_copyright(self, line):
        print("Copyright (C) 2011- Øyvind Jensen")

    def do_credits(self, line):
        print("Author:")
        print("Øyvind Jensen")
        print("oyvind.jensen@protonmail.com")

    def do_exit(self, line):
        print('Be well..')
        return True

    def __init__(self):
        cmd.Cmd.__init__(self)
        self.storage = shelve.open(self.filename, writeback = True)

    def do_EOF(self, line):
        print()
        return self.do_exit('')

    def complete(self, text, state):
        """Add a whitespace after word completion"""
        return cmd.Cmd.complete(self, text, state) + ' '


if __name__ == "__main__":
    CLI().cmdloop()