#!/usr/bin/env python

'''
M190

Copyright (C) 2019  Phillip A Carter

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 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 General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
'''

import sys
import time

from subprocess import Popen,PIPE

materialNum = int(float(sys.argv[1]))
timeout = 0.5

def get_material():
    return int(Popen(['halcmd getp plasmac_run.material-change-number'], stdout=PIPE, shell=True).communicate()[0].strip())

def set_material(material):
    Popen(['halcmd setp plasmac_run.material-change-number %d' %(material)], shell=True)

def get_change():
    return int(Popen(['halcmd getp plasmac_run.material-change'], stdout=PIPE, shell=True).communicate()[0].strip())

def set_change(value):
    Popen(['halcmd setp plasmac_run.material-change %d' %(value)], shell=True)

def set_timeout():
    Popen(['halcmd setp plasmac_run.material-change-timeout 1'], shell=True)

set_change(1)
start = time.time()
# if material already loaded set a phantom material
if materialNum == get_material():
    materialNum = materialNum * -1
set_material(materialNum)
while get_change() == 1:
    if time.time() > start + timeout:
        set_timeout()
        break
set_change(0)
exit()
