# 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 General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import cgi
import op_db_library as db

form = cgi.FieldStorage()
print 'Content-type: text/plain\n'

itemid = int(form.getvalue('item'))
item = db.get_item(itemid)
dist = None
if 'distname' in form:
    distname = form.getvalue('distname')
    if db.is_distributor_byname(distname):
        dist = db.get_distributor_byname(distname)
elif 'distid' in form:
    distid = int(form.getvalue('distid'))
    if db.is_distributor(distid):
        dist = db.get_distributor(distid)

if dist != None:
    dist_item = db.get_distributor_item(item,dist)
    print '%s,%d,%s,%.2f,%.2f,%s' % (dist.get_name(), dist.get_id(),dist_item.get_dist_item_id(), dist_item.get_wholesale_price(), dist_item.get_case_size(), dist_item.get_case_unit())

print 'Content-type: text/plain\n'
action = form.getvalue('action')
if action == 'add':
    if 'name' in form:
        distname = form.getvalue('name')
        if db.is_distributor_byname(distname):
            raise Exception ('distributor already exists')
        else:
            db.add_distributor(distname)
            dist = db.get_distributor_byname(distname)
            print '%d,%s' % (dist.get_id(),distname)
    else:
        raise Exception ('no distributor name given')
elif action == 'remove':
    distid = int(form.getvalue('id'))
    if not db.is_distributor(distid):
        raise Exception ('distributor not in database')
    else:
        dist = db.get_distributor(distid)
        print dist.get_name()
        db.remove_distributor(dist)
        
elif action == 'query':
    dist_list = [dist.get_name() for dist in db.get_distributors()]
    print ','.join(dist_list)
elif action == 'query-name':
    dist_list = [str(dist.get_id())+','+dist.get_name() for dist in db.get_distributors()]
    print '\n'.join(dist_list);
else:
    raise Exception ('invalid action')