#!/usr/bin/python
# comp.py
#       Compose a message
#
import os, sys
import imh

class Comp(imh.IMH_mixin):

    # We don't need anything from imap
    def need_server(self):
        return False

    # Process completions
    #
    # Returns ([to, ...], [cc, ...])
    # Enter a <string> to find completions.
    # Enter "cc <string>" to find completions, applied
    #  to the "cc" line.
    def completions(self):

        # No abook, so no completions
        if not self.abook:
            return (() ,())

        addrsto = []
        addrscc = []
        while True:
            # Show what's up so far
            if addrsto:
                sys.stdout.write("[To: %s]\n" % ((", ".join(addrsto)),))
            if addrscc:
                sys.stdout.write("[Cc: %s]\n" % ((", ".join(addrscc)),))

            # Get more?
            sys.stdout.write("To: ")
            l = sys.stdin.readline().strip()

            # Done
            if not l:
                return (addrsto, addrscc)

            # Add to which?
            if l.startswith("cc"):
                dest = addrscc
                l = l[2:].strip()
            else:
                dest = addrsto

            # Find matches
            cands = []
            for tup in self.abook:
                if l in str(tup):
                    cands.append(self.tup_addr(tup))

            # Nothin'
            if not cands:
                sys.stdout.write("Nothing matches '%s'\n" % (l,))
                continue

            # Nailed it
            if len(cands) == 1:
                dest.append(cands[0])
                continue

            # Choose?
            for idx,who in enumerate(cands):
                sys.stdout.write("%2d %s\n" % (idx, who))
            sys.stdout.write("Which: ")
            l = sys.stdin.readline().strip()
            if not l:
                continue
            try:
                idx = int(l)
                dest.append(cands[idx])
            except:
                continue

    # Fetch textual representation of this message,
    #  turn into our starting point for the composition
    def comp(self, subj=""):

        # To:, with completion
        addrsto,addrscc = self.completions()

        # Write out a template
        cfg = self.cfg
        fn = "%s/%s-%d" % (
         cfg.get("tmpdir", "/tmp"),
         os.getenv("USER"), os.getpid())
        f = open(fn, "w")
        f.write("From: %s <%s>\n" %
         (cfg.get("name", os.getenv("NAME")),
          cfg.get("address", os.getenv("USER"))) )
        f.write("To: %s\n" % (", ".join(addrsto),))
        if addrscc:
            f.write("Cc: %s\n" % (", ".join(addrscc),))
        f.write("Subject: %s\n" % (subj,))
        f.write("\n\n")
        f.close()
        return fn

    def run(self):

        # For completion
        self.load_abook()

        # Build our reply
        fn = self.comp()

        # Hand it to whatnow, starting in edit mode
        os.system("whatnow -e %s" % (fn,))

if __name__ == "__main__":
    i = Comp()
    i.main()
