package pml

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

	"go.devnw.com/ooxml"
)

type CT_ExtensionListModify struct {
	// Modify
	ModAttr *bool
	// Extension
	Ext []*CT_Extension
}

func NewCT_ExtensionListModify() *CT_ExtensionListModify {
	ret := &CT_ExtensionListModify{}
	return ret
}

func (m *CT_ExtensionListModify) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	if m.ModAttr != nil {
		start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "mod"},
			Value: fmt.Sprintf("%d", b2i(*m.ModAttr))})
	}
	e.EncodeToken(start)
	if m.Ext != nil {
		seext := xml.StartElement{Name: xml.Name{Local: "p:ext"}}
		for _, c := range m.Ext {
			e.EncodeElement(c, seext)
		}
	}
	e.EncodeToken(xml.EndElement{Name: start.Name})
	return nil
}

func (m *CT_ExtensionListModify) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	// initialize to default
	for _, attr := range start.Attr {
		if attr.Name.Local == "mod" {
			parsed, err := strconv.ParseBool(attr.Value)
			if err != nil {
				return err
			}
			m.ModAttr = &parsed
			continue
		}
	}
lCT_ExtensionListModify:
	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/presentationml/2006/main", Local: "ext"},
				xml.Name{Space: "http://purl.oclc.org/ooxml/presentationml/main", Local: "ext"}:
				tmp := NewCT_Extension()
				if err := d.DecodeElement(tmp, &el); err != nil {
					return err
				}
				m.Ext = append(m.Ext, tmp)
			default:
				office.Log("skipping unsupported element on CT_ExtensionListModify %v", el.Name)
				if err := d.Skip(); err != nil {
					return err
				}
			}
		case xml.EndElement:
			break lCT_ExtensionListModify
		case xml.CharData:
		}
	}
	return nil
}

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

// ValidateWithPath validates the CT_ExtensionListModify and its children, prefixing error messages with path
func (m *CT_ExtensionListModify) ValidateWithPath(path string) error {
	for i, v := range m.Ext {
		if err := v.ValidateWithPath(fmt.Sprintf("%s/Ext[%d]", path, i)); err != nil {
			return err
		}
	}
	return nil
}
