package sml

import (
	"encoding/xml"
	"fmt"
	"strconv"

	"go.devnw.com/ooxml"
)

type CT_Control struct {
	// Shape Id
	ShapeIdAttr uint32
	IdAttr      string
	// Control Name
	NameAttr *string
	// Embedded Control Properties
	ControlPr *CT_ControlPr
}

func NewCT_Control() *CT_Control {
	ret := &CT_Control{}
	return ret
}

func (m *CT_Control) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "shapeId"},
		Value: fmt.Sprintf("%v", m.ShapeIdAttr)})
	start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "r:id"},
		Value: fmt.Sprintf("%v", m.IdAttr)})
	if m.NameAttr != nil {
		start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "name"},
			Value: fmt.Sprintf("%v", *m.NameAttr)})
	}
	e.EncodeToken(start)
	if m.ControlPr != nil {
		secontrolPr := xml.StartElement{Name: xml.Name{Local: "ma:controlPr"}}
		e.EncodeElement(m.ControlPr, secontrolPr)
	}
	e.EncodeToken(xml.EndElement{Name: start.Name})
	return nil
}

func (m *CT_Control) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	// initialize to default
	for _, attr := range start.Attr {
		if attr.Name.Space == "http://schemas.openxmlformats.org/officeDocument/2006/relationships" && attr.Name.Local == "id" ||
			attr.Name.Space == "http://purl.oclc.org/ooxml/officeDocument/relationships" && attr.Name.Local == "id" {
			parsed, err := attr.Value, error(nil)
			if err != nil {
				return err
			}
			m.IdAttr = parsed
			continue
		}
		if attr.Name.Local == "shapeId" {
			parsed, err := strconv.ParseUint(attr.Value, 10, 32)
			if err != nil {
				return err
			}
			m.ShapeIdAttr = uint32(parsed)
			continue
		}
		if attr.Name.Local == "name" {
			parsed, err := attr.Value, error(nil)
			if err != nil {
				return err
			}
			m.NameAttr = &parsed
			continue
		}
	}
lCT_Control:
	for {
		tok, err := d.Token()
		if err != nil {
			return err
		}
		switch el := tok.(type) {
		case xml.StartElement:
			switch el.Name {
			case xml.Name{Space: "http://schemas.openxmlformats.org/spreadsheetml/2006/main", Local: "controlPr"},
				xml.Name{Space: "http://purl.oclc.org/ooxml/spreadsheetml/main", Local: "controlPr"}:
				m.ControlPr = NewCT_ControlPr()
				if err := d.DecodeElement(m.ControlPr, &el); err != nil {
					return err
				}
			default:
				office.Log("skipping unsupported element on CT_Control %v", el.Name)
				if err := d.Skip(); err != nil {
					return err
				}
			}
		case xml.EndElement:
			break lCT_Control
		case xml.CharData:
		}
	}
	return nil
}

// Validate validates the CT_Control and its children
func (m *CT_Control) Validate() error {
	return m.ValidateWithPath("CT_Control")
}

// ValidateWithPath validates the CT_Control and its children, prefixing error messages with path
func (m *CT_Control) ValidateWithPath(path string) error {
	if m.ControlPr != nil {
		if err := m.ControlPr.ValidateWithPath(path + "/ControlPr"); err != nil {
			return err
		}
	}
	return nil
}
